package example.servlet;

import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import example.model.App;
import example.model.User;
import org.owasp.jxt.UrlBuilder;

public class PostServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        User user = (User)req.getSession().getAttribute("user");
        User feedUser = null;

        if (user != null) {
            App app = (App)getServletContext().getAttribute("app");

            String feed = req.getParameter("feed");
            String message = req.getParameter("message");

            feedUser = app.getUser(feed);

            if (feedUser != null) {
                feedUser.addPost(user, new Date(), message);
            }
        }

        UrlBuilder url = new UrlBuilder("feed.jxt");

        if (feedUser != null && feedUser != user) {
            url.append("user", feedUser.name);
        }

        res.sendRedirect(res.encodeRedirectURL(url.toString()));
    }
}
